import './StudentList.scss'
import { localRequest } from '@/utils'
import StudentItem from './components/StudentItem/StudnetItem'
import { useEffect, useState } from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, ConfigProvider, Input, message, Empty } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { fetchGetStudentList } from '@/store/modules/teacher';
import { addStudentAPI, deleteStudentAPI } from '@/apis/teacher';

export default function StudentList() {
    const dispatch = useDispatch();
    const { user_status } = useSelector(state => state.user);
    const { studentList } = useSelector(state => state.teacher);
    const [stuArr, setStuArr] = useState([]);
    const [checkList, setCheckList] = useState([]);
    const [hasChecked, setHasChecked] = useState(false);
    const [checkedItemNum, setCheckedItemNum] = useState(0);
    const [allChecked, setAllChecked] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [newStuTel, setNewStuTel] = useState('');




    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleAddStu = async () => {
        setLoading(true);
        console.log(newStuTel);
        const res = await addStudentAPI([{
            class_id: user_status.class_id,
            telephone: newStuTel
        }], user_status.token);
        console.log(res);
        setNewStuTel('');
        dispatch(fetchGetStudentList(user_status.class_id, user_status.token));
        if(res.data[0].success){
            message.success(res.data[0].message);
        }else {
            message.error(res.data[0].message);
        }
        setLoading(false);
        setIsModalOpen(false);
    };

    const handleCancelAddStu = () => {
        setIsModalOpen(false);
    };

    const handleDeleteSingalStu = async (telephone) => {
        const res = await deleteStudentAPI([{
            "class_id": user_status.class_id,
            "telephone": telephone
        }], user_status.token);
        console.log(res);
        window.location.reload();
    }

    const handleDeleteStus = async () => {
        console.log(checkList);
        console.log(studentList);
        const data = [];
        studentList.forEach((ele, index) => {
            if (checkList[index]) data.push({
                class_id: user_status.class_id,
                telephone: ele.student_name
            })
        })
        const res = await deleteStudentAPI(data, user_status.token);
        console.log(res);
        window.location.reload();
    }

    // 当组件渲染完成时执行一次
    useEffect(() => {

        const getStuList = async function () {
            dispatch(fetchGetStudentList(user_status.class_id, user_status.token));


            // const res = await localRequest.get('/tec/tecStudentList.json');
            // setCheckList(res.data.map(() => false));
            // console.log(res.data);
            // setStuArr(res.data.map((ele, index) => {
            //     ele.id = index;
            //     return ele;
            // }))
        }

        getStuList();
    }, [])


    useEffect(() => {
        if (studentList.length !== 0) {
            setCheckList(Array(studentList.length).fill(false));
            // console.log(checkList);
        }
    }, [studentList]);

    useEffect(() => {
        if (checkList.length !== 0) {
            setHasChecked(checkList.reduce((a, b) => a || b), false);
            setCheckedItemNum(checkList.reduce((a, b) => b ? ++a : a, 0));
            setAllChecked(checkList.reduce((a, b) => a && b), true);
        }
    }, [checkList])


    const handleAllCheck = (e) => {
        setCheckList(checkList.map(() => e.target.checked))
    }

    const handleCancel = () => {
        setCheckList(checkList.map(() => false));
    }


    return (
        <div className='StudentList'>
            <nav
                style={{
                    height: hasChecked ? '40px' : '0'
                }}
            >
                <div className='all-check'>
                    <input
                        type='checkbox'
                        onChange={handleAllCheck}
                        checked={allChecked}
                        id='allcheckbox'
                    />
                    <label htmlFor='allcheckbox'>全选</label>
                    <div className='divide-line'></div>
                    <span>已选择{checkedItemNum}个学生</span>
                </div>
                <div className='delet-stu'>
                    <button onClick={handleDeleteStus}><DeleteOutlined /> 删除</button>
                    <div className='divide-line'></div>
                    <button onClick={handleCancel}>取消</button>
                </div>
            </nav>
            <main>
                {
                    studentList.length === 0 ||
                    (studentList[0].success ? studentList.map(ele =>
                        <StudentItem
                            key={ele.id}
                            info={ele}
                            ifChecked={checkList[ele.id]}
                            deleteStu={handleDeleteSingalStu}
                            onCheck={(key) => {
                                setCheckList(checkList.map((ele, index) => index === key ? !ele : ele));
                            }}
                        />
                    ) : <Empty
                        className='empty'
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                            <span>
                                课程还没有添加学生，点击右下角的图标添加
                            </span>
                        }
                    />
                    )
                }
            </main>
            <ConfigProvider
                theme={{
                    token: {
                        // Seed Token，影响范围大
                        colorPrimary: '#2486b9',
                        borderRadius: 5,

                        // 派生变量，影响范围小
                        // colorBgContainer: '#f6ffed',
                    },
                }}
            >
                <Button
                    type="primary"
                    onClick={showModal}
                    className='add-stu'
                >
                    <PlusOutlined />
                </Button>
                <Modal
                    title={<h3>新增学生</h3>}
                    open={isModalOpen}
                    onCancel={handleCancelAddStu}
                    footer={[
                        <Button key="back" onClick={handleCancelAddStu}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleAddStu}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newstutel'>请输入新增学生的手机号</label>
                    <Input id='newstutel' onInput={function (e) { setNewStuTel(e.target.value) }} value={newStuTel} />
                </Modal>
            </ConfigProvider>
        </div>
    )
}